/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-11-30     RT-Thread    first version
 */

/* rt-os 包含文件  */
#include <rtthread.h>
#define DBG_TAG "main"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>
#include <cstring>

/* 用户包含文件  */
#include "Log.h"
#include "IO_Ctrl.h"
#include "Motion.h"
#include "ActionQueue.h"
#include "MotionManage.h"

/* 全局句柄区 */
#include "GlobalVar.h"


/*
 *工作模式
 *默认工作与从机模式
 *主机工作与自动模式
 */

//.h


void ActQue1Task(void *parameter)
{

}

void create_action_queue_task()
{
    //启动所有的时序动作
    /*分别启动多个时序任务，是否全部启动
     */
    //创建10个任务
    rt_thread_create("ActQueTask",ActQue1Task, NULL, 512, 20, 5);


}




void UART2_Init(rt_uint32_t bauld){};
void UART3_Init(rt_uint32_t bauld){};
void CAN1_Init(rt_uint8_t addr){};
void CAN2_Init(rt_uint8_t addr){};
void Exti_Init(){};
void I2C1_Init(){};
void I2C2_Init(){};
void SPI1_Init(){};
void SPI2_Init(){};
void SPI3_Init(){};
/*
 * IO
 */
void PCF8574_Init(){};
void MT25Q_Init(){};
void TMC60_Init(){};




void STM32_BSP_Init()
{
    /* 片上外设初始化 */
    IO_Init();
    UART2_Init(57600);
    UART3_Init(57600);
    CAN1_Init(0xAA);
    CAN2_Init(0xAB);
    Exti_Init();
    I2C1_Init();
    I2C2_Init();
    SPI1_Init();
    SPI2_Init();
    SPI3_Init();


}

void SysClick_Init()
{

}
void Perphr_Init(){

    PCF8574_Init();
    MT25Q_Init();
    TMC60_Init();

};
void Module_Init(){

    //电机初始化
    //DummyMotorInit();
    //DummyPumpInit();
    //DummyEvInit();
};
void GlobalVar_Init(){
    machine_info.addr = 1;
};

void SelfTest(){};


void Fat_Usr_Init(){};

void Create_Task(){};
void Start_Task(){};


void OSInit()
{

}







void UpdateInit(){}




void Run_LED_Task(void *parameter)
{
    while(1)
    {
        Run_LED_OFF(NULL);
        DelayMs(500);
        Run_LED_ON(NULL);
        DelayMs(500);
    }
}

void Rrr_LED_Task(void *parameter)
{
    while(1)
    {
        DelayMs(500);
    }
}


void Create_MotorSem()
{
    /* 根据使用的驱动器数量  动态的创建电机信号量 */
    rt_uint8_t dirver_num = 0;

    for (rt_uint8_t dummy_motor_num = 1;
            dummy_motor_num < MOTOR_TOTAL_NUM;
            dummy_motor_num++)
    {
        if(MyBoardMotor(dummy_motor_num) == true)
        {
            dirver_num = MotorDiverNum(dummy_motor_num);

            if(dirver_num > 0 && dirver_num <= 6)
            {
                /* 电机驱动启动信号  */
                if(sem_motor[dirver_num].RunStart == NULL)
                {
                    char name[7] = "RunS_M";
                    itoa(dirver_num,&name[6],10);

                    sem_motor[dirver_num].RunStart =
                                        rt_sem_create(name,
                                                      0,
                                                      RT_IPC_FLAG_FIFO);

                    if(sem_motor[dirver_num].RunStart == NULL)
                    {
                        LOG_E("Motor_dirver_%d_run_start "
                                "semaphore create failed.",
                                dirver_num);
                    }
                    else
                    {
                        LOG_I("Motor_dirver_%d_run_start "
                                "semaphore create successed.",
                                dirver_num);
                    }
                }
                else
                {
                    LOG_E("Motor_dirver_%d_run_start semaphore "
                           "have been used twice.",
                           dirver_num);
                }
                /* 电机驱动完成信号  */
                if(sem_motor[dirver_num].RunFinished == NULL)
                {
                    char name[7] = "RunF_M";
                    itoa(dirver_num,&name[6],10);

                    sem_motor[dirver_num].RunFinished = rt_sem_create(name,
                                                              0,
                                                              RT_IPC_FLAG_FIFO);
                    if(sem_motor[dirver_num].RunFinished == NULL)
                    {
                        LOG_E("Motor_dirver_%d_run_finished "
                                "semaphore create failed.");
                    }
                    else
                    {
                        LOG_I("Motor_dirver_%d_run_finished "
                                "semaphore create successed.");
                    }
                }
                else
                {
                    LOG_E("Motor_dirver_%d_run_finished semaphore "
                           "have been used twice.",
                           dirver_num);
                }
            }
            else
            {
                LOG_E("Dummy_motor %s numbered M_%d is assigned motor driver "
                       "semaphore %d create failed there are no "
                       "motor_driver_%d.",
                       motor_info[dummy_motor_num].name,
                       dummy_motor_num,
                       dirver_num,
                       dirver_num);
            }
        }
    }
}


void Create_ErrSem()
{


}



void Create_LogMq()
{
    LogMqHandle = rt_mq_create("LogMq", 20, 100, RT_IPC_FLAG_PRIO);
//    char test[100];
//    rt_mq_send(LogMqHandle, test, sizeof(test));

}


/* 信号量 创建  进程间通信*/
void AppCreate_Sem()
{
    /* 36条电机信号量   12 * 3 */
    Create_MotorSem();
    /* 1条系统故障信号量 */
    Create_ErrSem();
    /* 32条阀泵动作信号量   16 * 2 */

    /* 动作序列和CAN通信信号量 */
}
//使用ulog 不再使用
/*
void LogMsg(char name[10],rt_uint8_t type,rt_uint8_t act,rt_int8_t state,rt_uint32_t para)
{
    LOG log_msg;
    strcpy(log_msg.name,name);
    log_msg.type = type;
    log_msg.act = act;
    log_msg.state = state;
    log_msg.para = para;
    rt_mq_send(LogMqHandle,&log_msg, sizeof(log_msg));
}
*/

void Create_LogTask()
{
    if(task.LogHandle == NULL)
    {
       task.LogHandle = rt_thread_create("LOG",
                                          Log_Task,
                                          NULL,
                                          512,
                                          20,
                                          5);
       if(task.LogHandle == NULL)
       {
           LOG_E("Run led task create failed.");
       }
       else
       {
           LOG_I("Run led task create successed.");
       }
    }

}
void Create_LEDTask()
{
    /* 两个LED任务  运行指示灯和报警灯  */
    if(task.RunLEDHandle == NULL)
    {
        task.RunLEDHandle = rt_thread_create("RUN_LED",
                                               Run_LED_Task,
                                               NULL,
                                               512,
                                               20,
                                               5);
        if(task.RunLEDHandle == NULL)
        {
            LOG_E("Run_led task create failed.");
        }
        else
        {
            LOG_I("Run_led task create successed.");
        }
    }

    if(task.ErrLEDHandle == NULL)
    {
        task.ErrLEDHandle = rt_thread_create("ERR_LED",
                                               Rrr_LED_Task,
                                               NULL,
                                               512,
                                               20,
                                               5);
        if(task.ErrLEDHandle == NULL)
        {
            LOG_E("Err_led task create failed.");
        }
        else
        {
            LOG_I("Err_led task create successed.");
        }
    }
}



void Create_MotorTask()
{
    /* 根据使用的驱动器数量  动态的创建电机任务线程 */
    rt_uint8_t dirver_num = 0;

    for (rt_uint8_t dummy_motor_num = 1;
            dummy_motor_num < MOTOR_TOTAL_NUM;
            dummy_motor_num++)
    {
        if(MyBoardMotor(dummy_motor_num) == true)
        {
            dirver_num = MotorDiverNum(dummy_motor_num);
            if(dirver_num > 0 && dirver_num < 7)
            {
                if(task.MotorDirverHandle[dirver_num] == NULL)
                {
                    char name[8] = "MOTOR_D";
                    itoa(dirver_num,&name[7],10);

                    task.MotorDirverHandle[dirver_num] =
                                    rt_thread_create(name,
                                                     Motor_D1_Task_Ptr[dirver_num],
                                                     NULL,
                                                     512,
                                                     20,
                                                     5);

                    if(task.MotorDirverHandle[dirver_num] == NULL)
                    {
                        LOG_I("Dummy_motor %s numbered M_%d is assigned motor_driver_%d failed.",
                                motor_info[dummy_motor_num].name,
                                dummy_motor_num,
                                dirver_num);
                        LOG_I("Motor_driver_%d task create failed.",
                                dirver_num);
                    }
                    else
                    {
                        LOG_I("Dummy_motor %s numbered M_%d is assigned motor_driver_%d successed.",
                                motor_info[dummy_motor_num].name,
                                dummy_motor_num,
                                dirver_num);
                        LOG_I("Motor_driver_%d task create successed.",
                                dirver_num);
                    }
                }
                else
                {
                    LOG_E("Motor driver %d have used by two dummy "
                            "motor at least.",
                            dirver_num);
                }

            }
            else
            {
                LOG_E("Dummy motor %d name %s assign motor driver %d failed "
                       " there are no motor driver %d.",
                       dummy_motor_num,
                       motor_info[dummy_motor_num].name,
                       dirver_num,
                       dirver_num);
            }
        }

    }
}


void Create_ActQueTask()
{
    /*  创建 20条动作 线程
     *  其中16条线程用于样本动作
     *  其中4条线程用于4条清洗动作
     */
    task.ActionQueueHandle[1] = rt_thread_create("ACT_Q1",
                                             Act_Q1_Task,
                                             NULL,
                                             5120,
                                             20,
                                             5);
}




void Startup_MotorTask()
{
    /* 根据创建的电机驱动的任务  动态的启动电机任务线程 */
    rt_err_t ret;
    for (int dirver_num = 1;
            dirver_num <= 6;
            dirver_num++)
    {
        if(task.MotorDirverHandle[dirver_num] != NULL)
        {
            ret = rt_thread_startup(task.MotorDirverHandle[dirver_num]);
            if(ret != RT_EOK)
            {
                LOG_E("Motor driver %d task startup failed.",
                       dirver_num);
            }
            LOG_I("Motor_driver_ %d task startup successed.",
                   dirver_num);
        }
    }
}


void Startup_LogTask()
{
    rt_err_t ret;
    if(task.LogHandle != NULL)
    {
        ret = rt_thread_startup(task.LogHandle);
        if(ret != RT_EOK)
        {
            LOG_E("Log task startup failed.");
        }
        LOG_I("Log task startup successed.");
    }

}

void Startup_LEDTask()
{
    rt_err_t ret;
    if(task.RunLEDHandle != NULL)
    {
        ret = rt_thread_startup(task.RunLEDHandle);
        if(ret != RT_EOK)
        {
            LOG_E("Run_LED  task startup failed.");
        }
        LOG_I("Run_LED task startup successed.");
    }
}

void Startup_ActQTask()
{
    /* 根据创建的动作序列的任务  动态的启动任务线程 */
    rt_err_t ret;
    if(task.ActionQueueHandle[1] != NULL)
    {
        ret = rt_thread_startup(task.ActionQueueHandle[1]);
        if(ret != RT_EOK)
        {
            LOG_E("Action_Queue 1 startup failed.");
        }
        LOG_I("Action_Queue 1 startup successed.");
    }

}
/* 应用层任务创建 */
void AppCreate_Task()
{
    //示例   创建一个LED任务
    Create_LEDTask();
    /*  创建电机任务 */
    Create_MotorTask();
    /*  创建阀泵任务 */

    /*  创建时序任务 */
    Create_ActQueTask();
}

/* 应用层任务启动 */
void AppStartup_Task()
{
    /* 启动所有创建任务 */

    //示例   启动一个LED任务
    Startup_LEDTask();
    /* 启动电机驱动器任务 */
    Startup_MotorTask();
    /* 启动动作序列任务 */
    Startup_ActQTask();
}

void Create_Startup_BaseTask()
{
    /* 日志相关
     * 1.日志消息队列创建
     * 2.日志任务创建
     * 3.日志任务启动
     * 使用ulog
     */
    /*
    Create_LogMq();
    Create_LogTask();
    Startup_LogTask();
    */
}

int main(void)
{
    /* 上电延时 */
    DelayMs(1000);
    /* 升级初始化 */
    UpdateInit();
    /* 片上外设初始化 */
    STM32_BSP_Init();
    /* 外围芯片初始化 */
    Perphr_Init();
    /* 全局变量初始化 */
    GlobalVar_Init();
    /* 模块初始化 */
    Module_Init();
    /* 设备自检 */
    SelfTest();
    /* 基础任务创建 */
    Create_Startup_BaseTask();
    /* 应用层信号量创建 */
    AppCreate_Sem();
    /* 应用层任务创建 */
    AppCreate_Task();
    /* 应用层任务启动 */
    AppStartup_Task();

    return RT_EOK;
}
